/*************************************************************************
 *
 *  Copyright (C) 2013 Florian Dang <florian.coin@gmail.com>
 *
 *  This file is part of NatusVerse.
 *
 *  NatusVerse is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  NatusVerse is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with NatusVerse.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

#include "raytracer/objects/sphere.h"

#include <stdio.h>
#include <cmath>
#include <cassert>

#include "raytracer/objects/object.h"

namespace raytracer
{
bool Sphere::Intersect(const Ray& ray, float& t) const
{
	Vector dist = center() - ray.start();
	float b = ray.direction() * dist;
	float radius0 = radius();
	float delta = b * b - dist * dist + radius0 * radius0;

	if (delta < 0.0f)
		return false;

	float d = sqrt(delta);
	float t0 = b - d;
	float t1 = b + d;
	bool retvalue = false;
	// TODO(coin): look for cancellation issues
	if ((t0 > Object::kEpsilon) && (t0 < t))
	{
		t = t0;
		retvalue = true;
	}
	if ((t1 > Object::kEpsilon) && (t1 < t))
	{
		t = t1;
		retvalue = true;
	}

    return retvalue;
}

Vector Sphere::Normal(const Point& intersection) const
{
	Vector vec_normal = intersection - center();
    vec_normal.Normalize();

    return vec_normal;
}

void Sphere::Print() const
{
	printf("sph: f{%.2f} o", radius());
	center().Print();
	printf(" ~ ");
	Object::material().Print();
}
}
